<?php

namespace CbjCode\General\Library\Traits;

use Illuminate\Http\JsonResponse;

/**
 * 后端增删改查复用类
 * Trait Backend
 * @package App\Library\Traits
 */
trait Backend
{
    /**
     * 查询数据
     * @return JsonResponse
     */
    public function index(){
        list($page,$limit,$where,$order,$sort) = $this->buildWhere();
        $field = $this->field;
        $list = $this->model->where($where)->orderBy($order,$sort)->paginate($limit, $field, $page);
        $data = ['page'=>$list->currentPage(),'pageSize'=>$list->perPage(),'items'=>$list->items(),'total'=>$list->total()];
        return jsonResult($data);
    }

    /**
     * 新增数据
     * @return bool|JsonResponse
     */
    public function store(){
        $params = $this->request->post();
        return $this->model->saveData($params);
    }

    /**
     * 显示数据
     */
    public function show(){
        $pk = $this->request->route("pk");
        $row = $this->model->find($pk);
        return jsonResult($row);
    }

    /**
     * 更新数据
     * @return JsonResponse
     */
    public function update(){
        $params = $this->request->post();
        $pk = $this->request->route("pk");
        return $this->model->saveData($params,$pk);
    }

    /**
     * 删除数据
     * @return JsonResponse
     */
    public function destroy(){
        $pk = $this->request->route("pk");
        return $this->model->delData($pk);
    }

}
